package com.cci.kangdao.service.impl;


import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.dao.SceneTechnicalConfirmationFaultCodeSymptomTDao;
import com.cci.kangdao.dao.SceneTechnicalConfirmationTDao;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.service.SceneTechnicalConfirmationService;
import com.cci.kangdao.utilTool.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("SceneTechnicalConfirmationService")
public class SceneTechnicalConfirmationServiceImpl implements SceneTechnicalConfirmationService {

	private Logger log = Logger.getLogger(this.getClass().getName());
	@Resource
	private SceneTechnicalConfirmationTDao sceneTechnicalConfirmationTDao;
	@Resource
	private SceneTechnicalConfirmationFaultCodeSymptomTDao sceneTechnicalConfirmationFaultCodeSymptomTDao;

	//技师提交现场技术确认信息接口
	@Transactional
	public ModelAndView submitSceneTechnicalConfirmationMsg(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		try {
			UserT userT = UserThreadLocal.get();
			String currentTime = LocalTimeUtil.getRealCurrentTime();
			JSONObject obj = new JSONObject();  //声明返给前端json对象
			long orderId = MapUtils.getLongValue(map,"OrderId",-1);
			String physicalTruthType = MapUtils.getString(map,"PhysicalTruthType","");
			String otherDescription = "";
			if(physicalTruthType.contains("5")){  //现场实际类型中有其他
				otherDescription = MapUtils.getString(map,"OtherDescription","");
			}
			List<Map<String,Object>> faultCodeList = new ArrayList<>();
			if(physicalTruthType.contains("4") && map.containsKey("FaultCodeList")){
				faultCodeList = (List<Map<String,Object>>)MapUtils.getObject(map,"FaultCodeList");
			}
			List<Map<String,Object>> symptomList = new ArrayList<>();
			if(physicalTruthType.contains("4") && map.containsKey("SymptomList")){
				symptomList = (List<Map<String,Object>>)MapUtils.getObject(map,"SymptomList");
			}
			String smn = MapUtils.getString(map,"SMN","");
			String orderNo = MapUtils.getString(map,"OrderNo","");
			String workHours = MapUtils.getString(map,"WorkHours","");
			String workMileages = MapUtils.getString(map,"WorkMileages","");
			String oemName = MapUtils.getString(map,"OEMName","");
			if(StringUtils.isEmpty(smn) || StringUtils.isEmpty(orderNo)|| StringUtils.isEmpty(oemName)|| orderId == -1 ||
			StringUtils.isEmpty(physicalTruthType)){
				obj.put("data", "");
				obj.put("status", 17);
				obj.put("msg", "缺少必要参数!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			if(StringUtils.isEmpty(workHours) && StringUtils.isEmpty(workMileages)){
				obj.put("data", "");
				obj.put("status", 17);
				obj.put("msg", "缺少发动机运转小时数或公里数!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			if(physicalTruthType.contains("4")){
				if(CollectionUtils.isEmpty(faultCodeList) && CollectionUtils.isEmpty(symptomList)){
					obj.put("data", "");
					obj.put("status", 17);
					obj.put("msg", "缺少故障码或者症状信息!");
					ParameterTool.writeResponse(response, obj.toString());
					return null;
				}
			}
			if(physicalTruthType.contains("5")){
				if(StringUtils.isEmpty(otherDescription)){
					obj.put("data", "");
					obj.put("status", 17);
					obj.put("msg", "缺少其他描述!");
					ParameterTool.writeResponse(response, obj.toString());
					return null;
				}
			}
			Map<String,Object> insertSelectiveMap = new HashMap<>();
			insertSelectiveMap.put("OrderId",orderId);
			insertSelectiveMap.put("PhysicalTruthType",physicalTruthType);
			if(physicalTruthType.contains("5")){
				insertSelectiveMap.put("OtherDescription",otherDescription);
			}
			insertSelectiveMap.put("Flag",0);
			insertSelectiveMap.put("Creator",userT.getId());
			insertSelectiveMap.put("CreateTime",currentTime);
			sceneTechnicalConfirmationTDao.insertSelective(insertSelectiveMap);
			long sceneTechnicalConfirmationTId = MapUtils.getLongValue(insertSelectiveMap,"ID");
			if(physicalTruthType.contains("4")){
				//调用公共方法
				insertSceneTechnicalConfirmationFaultCodeSymptomMapList(sceneTechnicalConfirmationTId,faultCodeList,symptomList,userT,currentTime);
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("smn",smn);
			jsonObject.put("userId",userT.getId());
			jsonObject.put("workOrderId",orderId);
			jsonObject.put("workOrderNo",orderNo);
			if(CollectionUtils.isNotEmpty(faultCodeList)){
				List<String> newFaultCodeList = new ArrayList<>();
				for(Map<String,Object> faultCodeMap : faultCodeList){
					String faultCode = MapUtils.getString(faultCodeMap,"FaultCode","");
					newFaultCodeList.add(faultCode);
				}
				jsonObject.put("faultCodeList",newFaultCodeList);
			}

			if(CollectionUtils.isNotEmpty(symptomList)){
				List<String> newSymptomList = new ArrayList<>();
				for(Map<String,Object> symptomMap : symptomList){
					String symptomName = MapUtils.getString(symptomMap,"SymptomName","");
					newSymptomList.add(symptomName);
				}
				jsonObject.put("symptomList",newSymptomList);
			}
			jsonObject.put("oem",oemName);
			jsonObject.put("workHours",workHours);
			jsonObject.put("workMileages",workMileages);
			//调用tsr接口
			Map<String,Object> mapp = new HashMap<>();
			try{
				log.info("技师提交现场技术确认信息接口，调用是否触发tsr报告接口");
				mapp = tsrTriggerReport(jsonObject.toString(),map);
			}catch (Exception e){
				String errorMsg = "技师提交现场技术确认信息接口，调用是否触发tsr报告接口失败："+ MapUtils.getString(mapp,"msg","");
				log.error(errorMsg);
			}
			int status = MapUtils.getIntValue(mapp,"status",-1);  //调用接口返回的状态码
			if(status != 0){
				String errorMsg = "技师提交现场技术确认信息接口，调用是否触发tsr报告接口失败："+ MapUtils.getString(mapp,"msg","");
				log.error(errorMsg);
			}
			obj.put("data", "");
			obj.put("status", 0);
			obj.put("msg", "success");
			ParameterTool.writeResponse(response, obj.toString());
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			ParameterTool.writeErrorResponse(response);
			// 主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return null;
	}


    //批量插入故障码和症状   公共方法
	private void insertSceneTechnicalConfirmationFaultCodeSymptomMapList(long sceneTechnicalConfirmationTId,List<Map<String,Object>> faultCodeList,List<Map<String,Object>> symptomList,UserT userT,String currentTime){
		List<Map<String,Object>> insertSceneTechnicalConfirmationFaultCodeSymptomMapList = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(faultCodeList)){
			for(Map<String,Object> faultCodeMap : faultCodeList){
				long faultCodeId = MapUtils.getLongValue(faultCodeMap,"FaultCodeId");
				String faultCode = MapUtils.getString(faultCodeMap,"FaultCode","");
				String SPN = MapUtils.getString(faultCodeMap,"SPN","");
				String FMI = MapUtils.getString(faultCodeMap,"FMI","");
				String FaultCodeDescription = MapUtils.getString(faultCodeMap,"FaultCodeDescription","");
				Map<String,Object> insertSceneTechnicalConfirmationFaultCodeSymptomMap = new HashMap<>();
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("SceneTechnicalConfirmationId",sceneTechnicalConfirmationTId);
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("Type",1);   //1:故障码，2:症状
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("FaultCodeSymptomId",faultCodeId);
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("FaultCode",faultCode);
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("SPN",SPN);
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("FMI",FMI);
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("FaultCodeDescription",FaultCodeDescription);
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("Flag",0);
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("Creator",userT.getId());
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("CreateTime",currentTime);
				insertSceneTechnicalConfirmationFaultCodeSymptomMapList.add(insertSceneTechnicalConfirmationFaultCodeSymptomMap);
			}
			if(CollectionUtils.isNotEmpty(insertSceneTechnicalConfirmationFaultCodeSymptomMapList)){
				sceneTechnicalConfirmationFaultCodeSymptomTDao.insertBatchSelective(insertSceneTechnicalConfirmationFaultCodeSymptomMapList);
				insertSceneTechnicalConfirmationFaultCodeSymptomMapList = new ArrayList<>();
			}
		}

		if(CollectionUtils.isNotEmpty(symptomList)){
			for(Map<String,Object> symptomMap : symptomList){
				long symptomId = MapUtils.getLongValue(symptomMap,"SymptomId");
				String symptomCategoryName = MapUtils.getString(symptomMap,"SymptomCategoryName","");
				String symptomName = MapUtils.getString(symptomMap,"SymptomName","");
				Map<String,Object> insertSceneTechnicalConfirmationFaultCodeSymptomMap = new HashMap<>();
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("SceneTechnicalConfirmationId",sceneTechnicalConfirmationTId);
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("Type",2);   //1:故障码，2:症状
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("FaultCodeSymptomId",symptomId);
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("SymptomCategoryName",symptomCategoryName);
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("SymptomName",symptomName);
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("Flag",0);
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("Creator",userT.getId());
				insertSceneTechnicalConfirmationFaultCodeSymptomMap.put("CreateTime",currentTime);
				insertSceneTechnicalConfirmationFaultCodeSymptomMapList.add(insertSceneTechnicalConfirmationFaultCodeSymptomMap);
			}
			if(CollectionUtils.isNotEmpty(insertSceneTechnicalConfirmationFaultCodeSymptomMapList)){
				sceneTechnicalConfirmationFaultCodeSymptomTDao.insertBatchSelective(insertSceneTechnicalConfirmationFaultCodeSymptomMapList);
			}
		}


	}


	//调用TSR接口   单独提出来
	public Map<String,Object> tsrTriggerReport(String data,Map<String,Object> map){
		HttpServletRequest request = (HttpServletRequest)map.get("request");

		Header userId = new BasicHeader("userid",request.getHeader("userid"));
		Header token = new BasicHeader("Authorization",request.getHeader("Authorization"));
		//获取配置文件中调用tsr项目   triggerReport
		String url = PropertiesUtil.getProperties("projectconfig.properties", "tsrTriggerReportUrl");
		//url ="http://192.168.0.87:8085/tsr/api/triggerReport";
		String response = HttpUtils.postJson(url,data, new ResponseHandler<String>() {
			@Override
			public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
				if (response.getStatusLine().getStatusCode() == 200) {
					HttpEntity httpEntity = response.getEntity();
					return  EntityUtils.toString(httpEntity);
				}else{
					log.error("异常，response：" + response);
				}
				return null;
			}
		},userId,token);
		Map<String,Object> returnMap = JsonUtils.toJavaObject(response,Map.class);
		return  returnMap;
	}


	//获取现场技术确认信息
    @Transactional
    @Override
    public ModelAndView getSceneTechnicalConfirmationMsg(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        try {
            JSONObject obj = new JSONObject();  //声明返给前端json对象
            long orderId = MapUtils.getLongValue(map,"OrderId",-1);
            if( orderId == -1){
                obj.put("data", "");
                obj.put("status", 17);
                obj.put("msg", "工单id不能为空!");
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }
            Map<String,Object> returnMap = new HashMap<>();
            List<Map<String,Object>> sceneTechnicalConfirmationMsgMapList = sceneTechnicalConfirmationTDao.getSceneTechnicalConfirmationByOrderId(orderId);
            if(CollectionUtils.isNotEmpty(sceneTechnicalConfirmationMsgMapList)){
				Map<String,Object> sceneTechnicalConfirmationMsgMap = sceneTechnicalConfirmationMsgMapList.get(0);
				if(MapUtils.isNotEmpty(sceneTechnicalConfirmationMsgMap)){
					returnMap.putAll(sceneTechnicalConfirmationMsgMap);
					long sceneTechnicalConfirmationMsgId = MapUtils.getLongValue(sceneTechnicalConfirmationMsgMap,"SceneTechnicalConfirmationId");
					List<Map<String,Object>> sceneTechnicalConfirmationFaultCodeSymptomTList = sceneTechnicalConfirmationFaultCodeSymptomTDao.getSceneTechnicalConfirmationFaultCodeSymptomTBySceneTechnicalConfirmationTId(sceneTechnicalConfirmationMsgId);
					if(CollectionUtils.isNotEmpty(sceneTechnicalConfirmationFaultCodeSymptomTList)){
						List<Map<String,Object>> faultCodeList = new ArrayList<>();
						List<Map<String,Object>> symptomList = new ArrayList<>();
						for(Map<String,Object> sceneTechnicalConfirmationFaultCodeSymptomT : sceneTechnicalConfirmationFaultCodeSymptomTList){
							int type = MapUtils.getIntValue(sceneTechnicalConfirmationFaultCodeSymptomT,"Type");   //1:故障码，2:症状
							long faultCodeSymptomId = MapUtils.getLongValue(sceneTechnicalConfirmationFaultCodeSymptomT,"FaultCodeSymptomId");
							long sceneTechnicalConfirmationFaultCodeSymptomTId = MapUtils.getLongValue(sceneTechnicalConfirmationFaultCodeSymptomT,"ID");
							if(type == 1){
								String faultCode = MapUtils.getString(sceneTechnicalConfirmationFaultCodeSymptomT,"FaultCode","");
								String spn = MapUtils.getString(sceneTechnicalConfirmationFaultCodeSymptomT,"SPN","");
								String fmi = MapUtils.getString(sceneTechnicalConfirmationFaultCodeSymptomT,"FMI","");
								String faultCodeDescription = MapUtils.getString(sceneTechnicalConfirmationFaultCodeSymptomT,"FaultCodeDescription","");
								Map<String,Object> faultCodeMap = new HashMap<>();
								faultCodeMap.put("SceneTechnicalConfirmationFaultCodeSymptomTId",sceneTechnicalConfirmationFaultCodeSymptomTId);
								faultCodeMap.put("FaultCodeId",faultCodeSymptomId);
								faultCodeMap.put("FaultCode",faultCode);
								faultCodeMap.put("SPN",spn);
								faultCodeMap.put("FMI",fmi);
								faultCodeMap.put("FaultCodeDescription",faultCodeDescription);
								faultCodeList.add(faultCodeMap);
							}
							if(type == 2){
								String symptomCategoryName = MapUtils.getString(sceneTechnicalConfirmationFaultCodeSymptomT,"SymptomCategoryName","");
								String symptomName = MapUtils.getString(sceneTechnicalConfirmationFaultCodeSymptomT,"SymptomName","");
								Map<String,Object> symptomMap = new HashMap<>();
								symptomMap.put("SceneTechnicalConfirmationFaultCodeSymptomTId",sceneTechnicalConfirmationFaultCodeSymptomTId);
								symptomMap.put("SymptomId",faultCodeSymptomId);
								symptomMap.put("SymptomCategoryName",symptomCategoryName);
								symptomMap.put("SymptomName",symptomName);
								symptomList.add(symptomMap);
							}
						}
						returnMap.put("FaultCodeList",faultCodeList);
						returnMap.put("SymptomList",symptomList);
					}
				}
			}

            obj.put("data", returnMap);
            obj.put("status", 0);
            obj.put("msg", "success");
            ParameterTool.writeResponse(response, obj.toString());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
            // 主动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return null;
    }



    //新增故障码症状接口
	@Override
	public ModelAndView insertFaultCodeSymptomList(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		try {
			UserT userT = UserThreadLocal.get();
			String currentTime = LocalTimeUtil.getRealCurrentTime();
			JSONObject obj = new JSONObject();  //声明返给前端json对象
			long sceneTechnicalConfirmationId = MapUtils.getLongValue(map,"SceneTechnicalConfirmationId",-1);
			if( sceneTechnicalConfirmationId == -1){
				obj.put("data", "");
				obj.put("status", 17);
				obj.put("msg", "现场技术确认信息表主键id不能为空!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			List<Map<String,Object>> faultCodeList = new ArrayList<>();
			if(map.containsKey("FaultCodeList")){
				faultCodeList = (List<Map<String,Object>>)MapUtils.getObject(map,"FaultCodeList");
			}
			List<Map<String,Object>> symptomList = new ArrayList<>();
			if(map.containsKey("SymptomList")){
				symptomList = (List<Map<String,Object>>)MapUtils.getObject(map,"SymptomList");
			}
			if(CollectionUtils.isEmpty(faultCodeList) && CollectionUtils.isEmpty(symptomList)){
				obj.put("data", "");
				obj.put("status", 17);
				obj.put("msg", "缺少故障码或者症状信息!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			insertSceneTechnicalConfirmationFaultCodeSymptomMapList(sceneTechnicalConfirmationId,faultCodeList,symptomList,userT,currentTime);
			obj.put("data", "");
			obj.put("status", 0);
			obj.put("msg", "success");
			ParameterTool.writeResponse(response, obj.toString());
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			ParameterTool.writeErrorResponse(response);
			// 主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return null;
	}
}
